<script setup lang="ts">
import { ref } from "vue";

// 使用 ref 获取 DOM 元素
const video = ref<HTMLVideoElement | null>(null);
const canvas = ref<HTMLCanvasElement | null>(null);
const photos = ref<HTMLDivElement | null>(null);
const stream = ref<MediaStream | null>(null);

// 按钮状态
const isCameraOn = ref(false);

async function getCamera() {
    try {
        // 确保 video 元素存在
        if (!video.value) throw new Error("Video element not found");

        stream.value = await navigator.mediaDevices.getUserMedia({
            video: {
                width: { ideal: 720 },
                height: { ideal: 480 },
                facingMode: "user",
            },
            audio: false,
        });

        video.value.srcObject = stream.value;
        isCameraOn.value = true;
    } catch (err) {
        console.error("获取摄像头失败:", err);
        alert(
            `无法访问摄像头: ${err instanceof Error ? err.message : String(err)}`,
        );
    }
}

function takePicture() {
    if (!stream.value || !canvas.value || !photos.value || !video.value) return;

    canvas.value.width = video.value.videoWidth;
    canvas.value.height = video.value.videoHeight;

    const context = canvas.value.getContext("2d");
    if (!context) return;

    context.drawImage(
        video.value,
        0,
        0,
        canvas.value.width,
        canvas.value.height,
    );

    const img = document.createElement("img");
    img.src = canvas.value.toDataURL("image/png");
    img.className = "photo";
    photos.value.appendChild(img);
}

function closeCamera() {
    if (stream.value) {
        stream.value.getTracks().forEach((track) => track.stop());
        stream.value = null;
    }

    if (video.value) {
        video.value.srcObject = null;
    }

    isCameraOn.value = false;
}
</script>

<template>
    <div id="videoContainer">
        <video ref="video" autoplay playsinline></video>
    </div>

    <div>
        <button @click="getCamera" :disabled="isCameraOn">开启摄像头</button>
        <button @click="takePicture" :disabled="!isCameraOn">拍照</button>
        <button @click="closeCamera" :disabled="!isCameraOn">关闭摄像头</button>
    </div>

    <canvas ref="canvas"></canvas>

    <div ref="photos"></div>
</template>
<style>
body {
    font-family: Arial, sans-serif;
    max-width: 800px;
    margin: 0 auto;
    padding: 20px;
}
#videoContainer {
    margin: 20px 0;
}
#video {
    width: 100%;
    max-width: 640px;
    background-color: #000;
}
#canvas {
    display: none;
}
button {
    padding: 10px 15px;
    margin-right: 10px;
    background-color: #4caf50;
    color: white;
    border: none;
    border-radius: 4px;
    cursor: pointer;
}
button:hover {
    background-color: #45a049;
}
#photos {
    display: flex;
    flex-wrap: wrap;
    margin-top: 20px;
}
.photo {
    width: 150px;
    margin: 5px;
    border: 1px solid #ddd;
}
</style>
